Translate switches containing fallthrough#38
Merged
nunoplopes merged 57 commits intoCpp2Rust:masterfrom Apr 29, 2026
Merged
Conversation
Rename visited_cases to visited_switch_cases_ and move it in class scope. VisitSwitchStmt always resets the set of visited switch cases. The old implementation was buggy because it saved reused SwitchCase pointers across translation units, making contain() return true for switches declared in other TUs.
C++ allows:
switch (x) {
default:
...
case 1:
...
}
In rust, default needs to be always on the last position, otherwise,
all values of x, even 1, will hit the default arm. Hence, the above C++
exmaple becomes:
match x {
1 => ...
_ => ...
}
As such, the algorithm for translating the cases becomes:
for (case: GetTopLevelSwitchCases()) {
if (ChainContainsDefault(case)) {
defer the conversion for the end
}
Convert(case)
Convert(GetSwitchArmBody(case))
}
Convert(deferred default)
ChainContainsDefault traverses the stacked case statements starting from
a top level case. For example:
case 2:
case 3:
default:
...
is deferred for the end of the match arms and is translated as:
_ => {}
i.e., drop the case 2, case 3 from the output, only convert as if it was
only default.
This reverts commit 67c099f.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
All switch tests pass now.
This PR translates switches containing fallthrough using the new
switch!macro defined inlibcc2rs-macros:It's necessary to translate the switch into a goto because later we will add support for jumping between switch arms using goto.
Below is an example of how the
switch!macro expands:Will be translated as:
Which will expand into (see comments attached to each arm):